package com.spark.demonetty.netty_demo.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author fuqiang
 * @Description 客户端处理类
 * @Date 2020/10/21
 */
public class TimeClientHander extends ChannelHandlerAdapter {

    public static final Logger logger = LoggerFactory.getLogger(TimeClientHander.class);
    private static final String Q = "QUERY TIME ORDER";
//    private final ByteBuf firstMessage;

    private int counter;
    private byte[] req;

    public TimeClientHander() {
       req = (Q + System.getProperty("line.separator")).getBytes();
//       firstMessage = Unpooled.buffer(req.length);
//       firstMessage.writeBytes(req);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf message = null;
        for (int i = 0; i < 100; i++) {
            message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String body = (String)msg;
        
        System.out.println("Now is :" + body + "; the counter is : "+ ++counter);

//        ByteBuf buf = (ByteBuf) msg;
//        byte[] req = new byte[buf.readableBytes()];
//        buf.readBytes(req);
//        String body = new String(req,"UTF-8");
    }
}
